﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Http.Filters;
using System.Net;
using System.Data.Entity.Validation;

namespace App.Web.Filter
{
    public class ErrorForMvcAttribute : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext filterContext)
        {
            string httpMethod = filterContext.RequestContext.HttpContext.Request.HttpMethod;
            var message = new System.Text.StringBuilder();
            message.AppendLine("HTTP-Method:" + httpMethod);

            System.Collections.Specialized.NameValueCollection formDate = filterContext.RequestContext.HttpContext.Request.Form;
            if (formDate != null && formDate.AllKeys.Length > 0)
            {
                message.AppendLine("参数信息:"); 
                foreach (var item in formDate.AllKeys)
                {
                    if (String.IsNullOrEmpty(item))
                        continue;
                    string value = formDate[item];
                    if (!String.IsNullOrEmpty(value) && value.Length > 1000)
                    {
                        value = value.Substring(0, 1000);
                    }
                    message.AppendLine(item + ":" + value);
                }
            }

            if (filterContext.Exception is DbEntityValidationException)
            {
                var error = filterContext.Exception as DbEntityValidationException;
                message.AppendLine(String.Empty);
                message.AppendLine(value: "实体异常信息：");
                foreach (var item in error.EntityValidationErrors)
                {
                    string fieldErrors = String.Join(",", item.ValidationErrors.Select(x => String.Format("{0}:{1}", x.PropertyName, x.ErrorMessage)));
                    message.AppendLine(fieldErrors);
                }
            }


            Core.Logging.ILogger iLogger = DependencyResolver.Current.GetService<App.Core.Logging.ILogger>();
            iLogger.Log(new Exception(message.ToString(), filterContext.Exception));

            base.OnException(filterContext);
        }
    }
}